package tcln.gxtx.client.widget.grid.editor;

import tcln.gxtx.client.utils.async.DeferredCommandScheduler;

import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.google.gwt.user.client.Command;

/**
 * A fast {@link CellEditor} which fixes an inconvenience in GXT that method {@link #doAutoSize()} is invoked everytime
 * this editor receives focus. It should be changed only when owner column's width changes.
 * 
 * @author Truong Chau Lien Ngoc (lienngoc@gmail.com)
 */
public class FastCellEditor extends CellEditor {
    private ColumnConfig ownerColumn;

    /**
     * @param field
     * @param ownerColumn
     */
    public FastCellEditor(Field<? extends Object> field) {
        super(field);
    }

    /**
     * Sets new value for ownerColumn.
     * 
     * @param ownerColumn
     *            the ownerColumn to set.
     */
    public void setOwnerColumn(ColumnConfig ownerColumn) {
        this.ownerColumn = ownerColumn;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void doAutoSize() {
        if (ownerColumn == null || getWidth() != ownerColumn.getWidth()) {
            DeferredCommandScheduler.scheduleOnce(new Command() {
                @Override
                public void execute() {
                    deferAutoSize();
                }
            });
        }
    }

    private void deferAutoSize() {
        super.doAutoSize();
    }
}
